package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.article.domain.*;
import cn.wolfcode.luowowo.article.query.StrategyDetailQuery;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IStrategyCommendService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.IStrategyTagService;
import cn.wolfcode.luowowo.cache.service.IStrategyStatisRedisService;
import cn.wolfcode.luowowo.cache.util.RedisKeys;
import cn.wolfcode.luowowo.cache.vo.StrategyStatisVO;
import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import cn.wolfcode.luowowo.common.exception.LogicException;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.search.query.SearchQueryObject;
import cn.wolfcode.luowowo.search.service.IStrategyTemplateService;
import cn.wolfcode.luowowo.search.vo.StatisVO;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RequestMapping("strategy")
@Controller
public class StrategyController {

    @Reference
    private IDestinationService destinationService;
    @Reference
    private IStrategyTagService strategyTagService;
    @Reference
    private IStrategyDetailService strategyDetailService;
    @Reference
    private IStrategyCommentService strategyCommentService;
    @Reference
    private IStrategyStatisRedisService strategyStatisRedisService;
    @Reference
    private IStrategyCommendService strategyCommendService;
    @Reference
    private IStrategyTemplateService strategyTemplateService;

    @RequestMapping("")
    public String index(Model model){
        model.addAttribute("commends",strategyCommendService.queryCommendTop5());
        //1.查zset里面的vo对象的key的集合(相当于zset的value)
        List<StrategyStatisVO> list = strategyStatisRedisService.getAllVOByZset();
        //2.区分国内外排名前10
        ArrayList<StrategyStatisVO> abroadCds = new ArrayList<>();      //国外
        ArrayList<StrategyStatisVO> unabroadCds = new ArrayList<>();    //国内
        //遍历出list中的vo对象
        for (StrategyStatisVO vo : list) {
            if (abroadCds.size()==10 && unabroadCds.size()==10){
                break;
            }
            //判断vo对象是不是国内的,且长度是否小于10
            if (vo.isIsabroad()){
                if (abroadCds.size()<10){
                    abroadCds.add(vo);
                }
            }else {
                if (unabroadCds.size()<10){
                    unabroadCds.add(vo);
                }
            }
        }
        model.addAttribute("abroadCds",abroadCds);
        model.addAttribute("unabroadCds",unabroadCds);

        //热门攻略查询 前 10
        List<StrategyStatisVO> hotCds  = strategyStatisRedisService.getHotTop10();
        model.addAttribute("hotCds", hotCds);

        //主题推荐: List<Map<String, Object>>

        //        //外层: list集合
        //内层: 左边:主题(id  name)  右边: 目的地集合  List集合中目的地:  (id name)
        //目前存在问题:
        //1:排序, 按主题关联到攻略的个数
        //2:只需要前面10个主题
        //3:目的地集合中数据去除重复

        List<Map<String, Object>> data = strategyTemplateService.getThemeCommend();
        model.addAttribute("themeCds", data);
        //查询条件

        //国内条件: 通过省份id 跟省份名 分  : list<StatisVO>  vo(id, name, count)
        List<StatisVO> chinas = strategyTemplateService.queryConditionGroup(SearchQueryObject.CONDITION_TYPE_UN_ABROAD);
        model.addAttribute("chinas", chinas);
        //国外条件: 通过国家id 国家的名 分
        List<StatisVO> abroads = strategyTemplateService.queryConditionGroup(SearchQueryObject.CONDITION_TYPE_ABROAD);
        model.addAttribute("abroads", abroads);

        //主题条件: 通过主题id 主题的名 分
        List<StatisVO> themes = strategyTemplateService.queryConditionGroup(SearchQueryObject.CONDITION_TYPE_THEME);
        model.addAttribute("themes", themes);

        return "strategy/index";
    }

    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") StrategyDetailQuery qo){
        List<Destination> toasts = destinationService.getToasts(qo.getDestId());
        Destination dest = null;
        if (toasts.size()>1){
            dest = toasts.remove(toasts.size() - 1);
        }else {
            dest = toasts.get(0);
        }
        model.addAttribute("toasts",toasts);
        model.addAttribute("dest",dest);
        List<StrategyTag> tags = strategyTagService.list();
        model.addAttribute("tags",tags);
        PageInfo pageInfo = strategyDetailService.query(qo);
        model.addAttribute("pageInfo",pageInfo);
        return "strategy/list";
    }

    @RequestMapping("/detail")
    public String detail(Model model,Long id,@UserParam UserInfo userInfo){
        StrategyDetail detail = strategyDetailService.get(id);
        StrategyContent content = strategyDetailService.getContent(id);
        detail.setStrategyContent(content);
        model.addAttribute("detail",detail);
        //阅读量+1
        strategyStatisRedisService.viewNumIncrease(id,1);

        /*if (userInfo==null){
            model.addAttribute("isFavor",false);
        }else {
            boolean favor = strategyStatisRedisService.favor(id, userInfo.getId());
            model.addAttribute("isFavor",!favor);
        }*/

        //热门排行分数+1:浏览数+评论数
        strategyStatisRedisService.addHotScores(RedisKeys.STRATEGY_STATIS_VO.join(id.toString()),1);
        model.addAttribute("vo",strategyStatisRedisService.getStrategyStatisVO(id));
        return "strategy/detail";
    }

    //评论
    @RequestMapping("/commentAdd")
    @ResponseBody
    public Object commentadd(StrategyComment strategyComment, @UserParam UserInfo userInfo){
        if (userInfo == null){
            throw new LogicException("请先登陆");
        }
        strategyComment.setUserId(userInfo.getId());
        strategyComment.setUsername(userInfo.getNickname());
        strategyComment.setCity(userInfo.getCity());
        strategyComment.setLevel(userInfo.getLevel());
        strategyComment.setHeadUrl(userInfo.getHeadImgUrl());
        strategyCommentService.save(strategyComment);
        //在redis服务中创建回复统计的方法
        strategyStatisRedisService.replyNumIncrease(strategyComment.getDetailId(),1);
        int replynum = strategyStatisRedisService.getStrategyStatisVO(strategyComment.getDetailId()).getReplynum();

        //热门排行分数:浏览数+评分数
        strategyStatisRedisService.addHotScores(RedisKeys.STRATEGY_STATIS_VO.join(strategyComment.getDetailId().toString()),1);


        return AjaxResult.SUCCESS.addData(replynum);
    }

    //评论分页
    @RequestMapping("/comment")
    public String commentPage(Model model,@ModelAttribute("qo") StrategyCommentQuery qo){
        model.addAttribute("page",strategyCommentService.query(qo));
        return "strategy/commentTpl";
    }

    //评论点赞
    @RequestMapping("/commentThumbUp")
    @ResponseBody
    public Object commentThumbUp(String toid,Long fromid){
        //toid:攻略内容的id
        //fromid:点赞用户的id
        strategyCommentService.thumbUp(toid,fromid);
        return AjaxResult.SUCCESS;
    }

    //收藏
    @RequestMapping("/favor")
    @ResponseBody
    public Object favor(HttpServletRequest request,Long sid, @UserParam UserInfo userInfo){
        if (userInfo==null){
            AjaxResult result = new AjaxResult(false, "请先登陆");
            result.setCode(102);
            return result;
        }
        //收藏还是取消收藏,根据传回来的true还是false来决定
        boolean ret = strategyStatisRedisService.favor(sid,userInfo.getId());
        request.getSession().setAttribute("isFavor",ret);

        /**
         * 排行加分
         * zset key 分数 value
         * 参数1: value 参数2:分数
         */
        strategyStatisRedisService.addCommendScores(RedisKeys.STRATEGY_STATIS_VO.join(sid.toString()),ret?1:-1);
        return new  AjaxResult(ret,"").addData(strategyStatisRedisService.getStrategyStatisVO(sid));
    }

    //攻略点赞
    @RequestMapping("/strategyThumbup")
    @ResponseBody
    public Object strategyThumbUp(Long sid,@UserParam UserInfo userInfo){
        if (userInfo==null){
            AjaxResult result = new AjaxResult(false, "请先登陆");
            result.setCode(102);
            return result;
        }
        boolean ret = strategyStatisRedisService.thumbUp(sid, userInfo.getId());
        /**
         * 排行加分
         * zset key 分数 value
         * 参数1: value 参数2:分数
         */
        if (ret){
            strategyStatisRedisService.addCommendScores(RedisKeys.STRATEGY_STATIS_VO.join(sid.toString()),1);
        }
        return new AjaxResult(ret,"").addData(strategyStatisRedisService.getStrategyStatisVO(sid));
    }

    @RequestMapping("/searchPage")
    public String searchPage(Model model,@ModelAttribute("qo")SearchQueryObject qo){

        model.addAttribute("page",strategyTemplateService.query(qo));

        return "strategy/searchPageTpl";
    }

}
